package com.jzm.filter;

import com.alibaba.fastjson2.JSON;
import com.jzm.dto.ResDTO;
import com.jzm.utils.JwtUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@WebFilter(urlPatterns = "/*")
public class FSFilter implements Filter {
    private static List<String> excludeUris = new ArrayList<>();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("application.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
            String property = properties.getProperty("exclude.uris");
            excludeUris = List.of(property.split(","));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        String requestURI = req.getRequestURI();

        //判断uri是否在免登校验列表里
        if(!excludeUris.contains(requestURI)){
            String token = req.getHeader("token");
            if(token == null || token.trim().equals("")){
                processToken(res, 408, "token can not by null");
            }else{
                try{
                    //用户ID，用户详情信息可以到mysql或者redis去读取
                    String userName = JwtUtil.validateToken(token);
                }catch (Exception e){
                    //日志记录异常信息
                    processToken(res, 410, "token not exists");
                }
            }
        }
        chain.doFilter(request,response);
    }

    private static void processToken(HttpServletResponse res, int code, String token_can_not_by_null) throws IOException {
        PrintWriter writer = res.getWriter();
        ResDTO resDTO = new ResDTO();
        resDTO.setCode(code);
        resDTO.setMsg(token_can_not_by_null);
        writer.write(JSON.toJSONString(resDTO));
        writer.flush();
        writer.close();
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
